<template>
  <div style="width: 100%; height: 100%; min-height: 300px;">
    <!-- 按钮区域 -->
    <div class="button-area">
      <el-button
        type="primary"
        size="small"
        :icon="Plus"
        @click="handleAddCard"
      >
        {{ t('datacenter.relateddataPage.addCard') }}
      </el-button>

      <!-- 列数选择下拉菜单 -->
      <el-dropdown class="dropdown-control" trigger="click">
        <span class="el-dropdown-link">
          <el-button type="primary" size="small" :icon="Grid">
            {{ columnCount }}{{ t('datacenter.relateddataPage.columns') }}
          </el-button>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="columnCount = 1">1{{ t('datacenter.relateddataPage.columns') }}</el-dropdown-item>
            <el-dropdown-item @click="columnCount = 2">2{{ t('datacenter.relateddataPage.columns') }}</el-dropdown-item>
            <el-dropdown-item @click="columnCount = 3">3{{ t('datacenter.relateddataPage.columns') }}</el-dropdown-item>
            <el-dropdown-item @click="columnCount = 4">4{{ t('datacenter.relateddataPage.columns') }}</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 卡片区域 -->
    <div
      class="cards-container"
      :style="{ gridTemplateColumns: `repeat(${columnCount}, 1fr)` }"
    >
      <el-card v-for="(card, index) in cards" :key="card.id" class="data-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">{{ t('datacenter.relateddataPage.d2Related') }} {{ index + 1 }}</span>
            <div class="card-actions">
              <el-button size="small" :icon="Setting" @click="handleSetting(index)">{{ t('datacenter.relateddataPage.settingButton') }}</el-button>
              <el-button size="small" type="success" :icon="VideoPlay" @click="handleStart(index)">{{ t('datacenter.relateddataPage.startStatisticsButton') }}</el-button>
              <el-button size="small" type="danger" :icon="VideoPause" @click="handleStop(index)">{{ t('datacenter.relateddataPage.stopStatisticsButton') }}</el-button>
              <el-button size="small" type="warning" :icon="Delete" @click="handleRemoveCard(index)">{{ t('datacenter.relateddataPage.removeCardButton') }}</el-button>
            </div>
          </div>
        </template>
        <div class="card-content">
          <!-- 显示图表 -->
          <template v-if="card.processedData && card.processedData.devicesData && card.processedData.devicesData.length > 0">
            <!-- 线状图 -->
            <TwoDLineChart
              v-if="card.settings.displayMode === 'line'"
              :title="''"
              :xAxisField="card.settings.xAxisParam"
              :xAxisUnit="card.settings.xAxisUnit"
              :yAxisField="card.settings.yAxisParam"
              :yAxisUnit="card.settings.yAxisUnit"
              :devicesData="card.processedData.devicesData"
              style="height: 100%; min-height: 200px;"
            />
            <!-- 柱状图 -->
            <TwoDColumeChart
              v-else-if="card.settings.displayMode === 'bar'"
              :title="''"
              :xAxisField="card.settings.xAxisParam"
              :xAxisUnit="card.settings.xAxisUnit"
              :yAxisField="card.settings.yAxisParam"
              :yAxisUnit="card.settings.yAxisUnit"
              :devicesData="card.processedData.devicesData"
              style="height: 100%; min-height: 200px;"
            />
            <!-- 散点图 -->
            <TwoDPointChart
              v-else
              :title="''"
              :xAxisField="card.settings.xAxisParam"
              :xAxisUnit="card.settings.xAxisUnit"
              :yAxisField="card.settings.yAxisParam"
              :yAxisUnit="card.settings.yAxisUnit"
              :devicesData="card.processedData.devicesData"
              style="height: 100%; min-height: 200px;"
            />
          </template>
          <!-- 加载状态 -->
          <div v-else-if="card.loading" class="loading-content">
            <el-icon :size="36"><Loading /></el-icon>
            <span style="margin-left: 10px;">{{ t('datacenter.relateddataPage.loadingText') }}</span>
          </div>
          <!-- 占位内容 -->
          <div v-else class="placeholder-content">
            <p>{{ t('datacenter.relateddataPage.placeholderContent') }}</p>
            <p>卡片 {{ index + 1 }}</p>
            <p v-if="card.isStatisticsStarted">{{ t('datacenter.relateddataPage.statisticsInProgress') }}</p>
            <p v-else>{{ t('datacenter.relateddataPage.clickToStartStatistics') }}</p>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 设置表单对话框 -->
    <el-dialog
      :draggable="true"
      v-model="dialogVisible"
      :title="t('datacenter.relateddataPage.chartSetting')"
      width="500px"
      :before-close="handleClose"
    >
      <el-form :model="formData" label-width="100px">
        <!-- 显示模式 -->
        <el-form-item :label="t('datacenter.relateddataPage.displayMode')">
          <el-radio-group v-model="formData.displayMode">
            <el-radio :label="'line'">{{ t('datacenter.relateddataPage.lineChart') }}</el-radio>
            <el-radio :label="'bar'">{{ t('datacenter.relateddataPage.barChart') }}</el-radio>
            <el-radio :label="'point'">{{ t('datacenter.relateddataPage.pointChart') }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 统计模式 -->
        <el-form-item :label="t('datacenter.relateddataPage.statisticsMode')">
          <el-radio-group v-model="formData.statisticsMode">
            <el-radio :label="'max'">{{ t('datacenter.relateddataPage.maxValue') }}</el-radio>
            <el-radio :label="'avg'">{{ t('datacenter.relateddataPage.avgValue') }}</el-radio>
            <el-radio :label="'sum'">{{ t('datacenter.relateddataPage.sumValue') }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- X轴参数 -->
        <el-form-item :label="t('datacenter.relateddataPage.xAxisParam')">
          <el-select v-model="formData.xAxisParam" :placeholder="t('datacenter.relateddataPage.xAxisParam')">
            <el-option v-for="param in xAxisParams" :key="param.val" :label="param.label+'('+param.unit+')'" :value="param.val"></el-option>
          </el-select>
        </el-form-item>

        <!-- Y轴参数 -->
        <el-form-item :label="t('datacenter.relateddataPage.yAxisParam')">
          <el-select v-model="formData.yAxisParam" :placeholder="t('datacenter.relateddataPage.yAxisParam')">
            <el-option v-for="param in yAxisParams" :key="param.val" :label="param.label+'('+param.unit+')'" :value="param.val"></el-option>
          </el-select>
        </el-form-item>

        <!-- X轴过滤方式 -->
        <el-form-item :label="t('datacenter.relateddataPage.xFilterMode')">
          <el-radio-group v-model="formData.xFilterMode">
            <el-radio :label="'auto'">{{ t('datacenter.relateddataPage.autoFilter') }}</el-radio>
            <el-radio :label="'custom'">{{ t('datacenter.relateddataPage.customFilter') }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- X轴自定义过滤条件 -->
        <el-form-item v-if="formData.xFilterMode === 'custom'" :label="t('datacenter.relateddataPage.xAxisMin')">
          <el-input v-model="formData.xMin" type="number"></el-input>
        </el-form-item>
        <el-form-item v-if="formData.xFilterMode === 'custom'" :label="t('datacenter.relateddataPage.xAxisMax')">
          <el-input v-model="formData.xMax" type="number"></el-input>
        </el-form-item>

        <!-- Y轴过滤方式 -->
        <el-form-item :label="t('datacenter.relateddataPage.yFilterMode')">
          <el-radio-group v-model="formData.yFilterMode">
            <el-radio :label="'auto'">{{ t('datacenter.relateddataPage.autoFilter') }}</el-radio>
            <el-radio :label="'custom'">{{ t('datacenter.relateddataPage.customFilter') }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- Y轴自定义过滤条件 -->
        <el-form-item v-if="formData.yFilterMode === 'custom'" :label="t('datacenter.relateddataPage.yAxisMin')">
          <el-input v-model="formData.yMin" type="number"></el-input>
        </el-form-item>
        <el-form-item v-if="formData.yFilterMode === 'custom'" :label="t('datacenter.relateddataPage.yAxisMax')">
          <el-input v-model="formData.yMax" type="number"></el-input>
        </el-form-item>

        <!-- Y值是否累加 -->
        <el-form-item :label="t('datacenter.relateddataPage.isYAccumulate')">
          <el-radio-group v-model="formData.isYAccumulate">
            <el-radio :label="true">{{ t('datacenter.relateddataPage.confirmButton') }}</el-radio>
            <el-radio :label="false">{{ t('datacenter.relateddataPage.cancelButton') }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">{{ t('datacenter.relateddataPage.cancelButton') }}</el-button>
        <el-button type="primary" @click="handleSaveSettings">{{ t('datacenter.relateddataPage.confirmButton') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, toRaw, computed, onUnmounted } from "vue";
import { ElButton, ElDialog, ElForm, ElFormItem, ElRadioGroup, ElRadio, ElSelect, ElOption, ElInput, ElMessage, ElLoading } from "element-plus";
import { Plus, Grid, Setting, VideoPlay, VideoPause, Delete, Loading } from '@element-plus/icons-vue';
import { useI18n } from "vue-i18n";
import { getAggregateParams } from "@/views/dataCenter/relateddata/tools/aggregateTool";
import { getIotDataSummaryPageListApi } from "@/api/iotdata/iotdata";
import TwoDLineChart from "@/views/components/aecharts/TwoDLineChart.vue";
import TwoDColumeChart from "@/views/components/aecharts/TwoDColumeChart.vue";
import TwoDPointChart from "@/views/components/aecharts/TwoDPointChart.vue";
const props = defineProps({
  params: {
    type: Object,
    required: true
  },
  deviceOptions: {
    type: Array,
    required: false,
    default: [],
  }
});

const { t } = useI18n();

// 定义卡片数据接口
interface CardItem {
  id: number;
  isStatisticsStarted: boolean;
  settings: any;
  data?: Array<[string, number, number]>; // 原始数据 [deviceNo, xValue, yValue]
  processedData?: any; // 处理后的数据
  page: number; // 当前页码
  hasMore: boolean; // 是否有更多数据
  loading?: boolean; // 是否加载中
  worker?: Worker; // Web Worker实例
  timer?: number; // 定时器ID
}

// 统计模式映射
type StatisticsMode = 'max' | 'avg' | 'sum';
const statisticsModeMap: Record<StatisticsMode, number> = {
  max: 0,
  avg: 1,
  sum: 2
};

const columnCount = ref(1); // 默认列数为1
const cards = ref<CardItem[]>([]);
let cardIdCounter = 1;
const dialogVisible = ref(false);
const currentCardIndex = ref(-1);
const DEFAULT_PAGE_SIZE = 10000; // 默认分页大小
// 使用props中的插值点数，默认为100
const getInterpolatePoints = () => {
  return props.params?.interpolatePoints || 1000;
};

// 模拟X轴和Y轴参数数据
const xAxisParams = ref([]);
const yAxisParams = ref([]);

// 从参数中提取标签和单位的辅助函数
const extractLabelAndUnit = (params: any[], targetVal: string) => {
  const param = params.find(p => p.val === targetVal);
  if (param) {
    return param.unit ? `${param.label}(${param.unit})` : param.label;
  }
  return '';
};

// 表单数据
const formData = reactive({
  displayMode: 'line', // 显示模式：line(线状), bar(柱状), point(点状)
  statisticsMode: 'max', // 统计模式：max(最大值), avg(平均值), sum(累加值)
  xAxisParam: '', // X轴参数
  xAxisUnit:'',   //x轴单位
  yAxisParam: '', // Y轴参数
  yAxisUnit:'',   //y轴单位
  xFilterMode: 'auto', // X轴过滤方式：auto(自动), custom(自定义)
  yFilterMode: 'auto', // Y轴过滤方式：auto(自动), custom(自定义)
  xMin: 0, // X轴最小值
  xMax: 100, // X轴最大值
  yMin: 0, // Y轴最小值
  yMax: 100, // Y轴最大值
  isYAccumulate: false // Y值是否累加
});

watch(
  () => props,
  (newVal) => {
    console.log(toRaw(newVal));
    if(newVal.params.productKey){
      xAxisParams.value = getAggregateParams(newVal.params.productKey,true)
      yAxisParams.value = getAggregateParams(newVal.params.productKey,false)
      console.log(toRaw(xAxisParams.value));
    }

  },{
    deep:true, immediate: true
  }
);

// 新增卡片按钮点击事件
const handleAddCard = () => {
  cards.value.push({
    id: cardIdCounter++,
    isStatisticsStarted: false,
    settings: { ...formData },
    data: [],
    processedData: null,
    page: 1,
    hasMore: true,
    loading: false
  });
//   ElMessage({
//     type: 'success',
//     message: t('datacenter.relateddataPage.cardAdded')
//   });
};

// 设置按钮点击事件
const handleSetting = (index: number) => {
  currentCardIndex.value = index;
  // 加载当前卡片的设置
  if (cards.value[index].settings) {
    Object.assign(formData, cards.value[index].settings);
  } else {
    // 使用默认设置
    Object.assign(formData, {
      displayMode: 'line',
      statisticsMode: 'max',
      xAxisParam: '',
      yAxisParam: '',
      xFilterMode: 'auto',
      yFilterMode: 'auto',
      xMin: 0,
      xMax: 100,
      yMin: 0,
      yMax: 100,
      isYAccumulate: false
    });
  }
  dialogVisible.value = true;
};

// 开始统计按钮点击事件
const handleStart = async (index: number) => {
  const card = cards.value[index];
  card.isStatisticsStarted = true;
  card.page = 1;
  card.data = [];
  card.hasMore = true;
  card.processedData = null;

  // 创建Worker（如果需要）
  if (card.settings.displayMode === 'line' || card.settings.displayMode === 'bar') {
    if (!card.worker) {
      card.worker = new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' });

      // 监听Worker消息
      card.worker.onmessage = (e: MessageEvent) => {
        if (e.data.type === 'result') {
          // 处理统计结果
          updateProcessedData(index, e.data.data);
        } else if (e.data.type === 'error') {
          console.error('Worker error:', e.data.error);
          ElMessage.error('数据处理失败: ' + e.data.error);
        }
      };
    }
  }

  // 开始顺序获取数据
  await  fetchDataSequentially(index);
};

// 顺序获取数据函数
const fetchDataSequentially = async (index: number) => {
  const card = cards.value[index];
  if (!card.isStatisticsStarted || !card.hasMore) return;

  // 获取数据
  await fetchData(index);

  // 如果是线图或柱图，需要等所有数据获取完成后再处理
  if (card.settings.displayMode === 'line' || card.settings.displayMode === 'bar') {
    if (card.hasMore) {
      // 等待50ms后继续获取
      setTimeout(() => {
        fetchDataSequentially(index);
      }, 50);
    } else {
      // 所有数据获取完成，一次性推给webworker处理
      processDataWithWorker(index);
    }
  } else {
    // 对于散点图，每次获取数据后立即处理并渲染
    processPointData(index);

    if (card.hasMore) {
      // 等待50ms后继续获取
      setTimeout(() => {
        fetchDataSequentially(index);
      }, 50);
    }
  }
};

// 停止统计按钮点击事件
const handleStop = (index: number) => {
  const card = cards.value[index];
  card.isStatisticsStarted = false;

  // 清理定时器
  if (card.timer) {
    clearInterval(card.timer);
    card.timer = undefined;
  }

  // 清理Worker
  if (card.worker) {
    card.worker.terminate();
    card.worker = undefined;
  }

  // 可以保留已处理的数据继续显示
  // 如果需要清空数据，可以取消下面两行的注释
  // card.data = [];
  // card.processedData = null;
};

// 获取数据
const fetchData = async (index: number) => {
  const card = cards.value[index];
  if (card.loading || !card.hasMore || !card.isStatisticsStarted) return;

  card.loading = true;

  try {
    // 准备请求参数
    const requestParams = {
      page: card.page,
      pageSize: DEFAULT_PAGE_SIZE,
      timeType: props.params.timeType,
      timeRange: props.params.timeRange,
      recent: props.params.recent,
      deviceNos: props.params.deviceNos,
      distributeTableId: props.params.distributeTableId,
      dimension: 2, // 二维
      xAxisParam: card.settings.xAxisParam,
      yAxisParam: card.settings.yAxisParam,
      xFilterMode: card.settings.xFilterMode,
      yFilterMode: card.settings.yFilterMode,
      xMin: card.settings.xFilterMode === 'custom' ? card.settings.xMin : undefined,
      xMax: card.settings.xFilterMode === 'custom' ? card.settings.xMax : undefined,
      yMin: card.settings.yFilterMode === 'custom' ? card.settings.yMin : undefined,
      yMax: card.settings.yFilterMode === 'custom' ? card.settings.yMax : undefined
    };
    card.settings.xAxisUnit = extractLabelAndUnit(xAxisParams.value, card.settings.xAxisParam);
    card.settings.yAxisUnit = extractLabelAndUnit(yAxisParams.value, card.settings.yAxisParam);
    // 调用API
    const response = await getIotDataSummaryPageListApi(requestParams);
    const result = response.data as { list: Array<[string, number, number]>; total: number };

    // 添加数据
    if (result.list && result.list.length > 0) {
      card.data = [...card.data, ...result.list];

      // 更新页码
      card.page++;

      // 检查是否还有更多数据
      card.hasMore = card.data.length < result.total;
    } else {
      card.hasMore = false;
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败');
    // 出错时设置hasMore为false，避免无限重试
    card.hasMore = false;
  } finally {
    card.loading = false;
  }
};

// 使用Worker处理数据
const processDataWithWorker = (index: number) => {
  const card = cards.value[index];
  if (!card.worker || card.data.length === 0) return;
  // 发送数据到Worker
  // 确保数据可以被结构化克隆算法序列化
  const serializableData = {
    type: 'process' as const,
    // 深拷贝数据数组，确保没有不可序列化的引用
    data: JSON.parse(JSON.stringify(card.data)) as Array<[string, number, number]>,
    aggregateMode: statisticsModeMap[card.settings.statisticsMode as StatisticsMode] || 0,
    numberOfPoints: getInterpolatePoints(),
    showMode: 0,
    isYSum: card.settings.isYAccumulate
  };

  // 发送可序列化的数据到Worker
  card.worker.postMessage(serializableData);
};

// 处理散点图数据
const processPointData = (index: number) => {
  const card = cards.value[index];
  if (card.data.length === 0) return;

  // 按设备分组
  const deviceMap = new Map<string, Array<{ x: number; y: number }>>();

  card.data.forEach(item => {
    const deviceNo = item[0];
    const x = item[1];
    const y = item[2];

    if (!deviceMap.has(deviceNo)) {
      deviceMap.set(deviceNo, []);
    }
    deviceMap.get(deviceNo)!.push({ x, y });
  });

  // 转换为图表需要的格式
  const devicesData = Array.from(deviceMap.entries()).map(([deviceNo, points]) => ({
    deviceId: deviceNo,
    deviceName: deviceNo,
    data: points
  }));

  card.processedData = { devicesData };
};

// 更新处理后的数据
const updateProcessedData = (index: number, result: any) => {
  const card = cards.value[index];

  // 转换为图表需要的格式
  const devicesData = result.computeResult.map((item: any) => ({
    deviceId: item.sn,
    deviceName: item.sn,
    data: item.xys.map((point: [number, number]) => ({ x: point[0], y: point[1] }))
  }));

  card.processedData = {
    devicesData,
    max: result.max,
    min: result.min
  };
};


// 保存设置
const handleSaveSettings = () => {
  if (currentCardIndex.value !== -1) {
    const card = cards.value[currentCardIndex.value];
    const oldDisplayMode = card.settings?.displayMode;
    card.settings = { ...formData };

    // 如果正在统计并且有数据
    if (card.isStatisticsStarted && card.data.length > 0) {
      // 处理模式切换的情况
      if (oldDisplayMode && oldDisplayMode !== card.settings.displayMode) {
        // 停止当前的统计流程
        handleStop(currentCardIndex.value);
        // 重新开始统计
        handleStart(currentCardIndex.value);
      } else {
        // 相同模式下重新处理数据
        if (card.settings.displayMode === 'line' || card.settings.displayMode === 'bar') {
          // 线图和柱状图需要一次性处理所有数据
          processDataWithWorker(currentCardIndex.value);
        } else {
          // 散点图重新处理
          processPointData(currentCardIndex.value);
        }
      }
    }
  }
  dialogVisible.value = false;
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
};

// 添加移除卡片的方法
const handleRemoveCard = (index: number) => {
  const card = cards.value[index];

  // 清理定时器
  if (card.timer) {
    clearInterval(card.timer);
  }

  // 清理Worker
  if (card.worker) {
    card.worker.terminate();
  }

  // 移除卡片
  cards.value.splice(index, 1);
  ElMessage({
    type: 'success',
    message: t('datacenter.relateddataPage.cardRemoved')
  });
};

// 组件卸载时清理所有资源
onUnmounted(() => {
  cards.value.forEach(card => {
    if (card.timer) {
      clearInterval(card.timer);
    }
    if (card.worker) {
      card.worker.terminate();
    }
  });
});
</script>

<style scoped lang="scss">
.button-area {
  display: flex;
  margin-bottom: 16px;
  gap: 10px;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.cards-container {
  display: grid;
  gap: 20px;
  width: 100%;
}

.data-card {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 200px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.card-title {
  font-weight: bold;
}

.card-actions {
  display: flex;
  gap: 5px;
}

.card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.placeholder-content {
  text-align: center;
  padding: 20px;
  color: #606266;
}

.loading-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  min-height: 200px;
}

/* 确保图表容器占满卡片内容区域 */
:deep(.two-d-line-chart-container),
:deep(.two-d-colume-chart-container),
:deep(.two-d-point-chart-container) {
  height: 100%;
  min-height: 200px;
}
</style>
